
"""采购生成付款申请明细"""

from datetime import datetime

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class Purchase(models.Model):
    _inherit = 'purchase.order'

    @api.multi
    def button_confirm(self):
        res = super().button_confirm()
        for purchase in self:
            purchase.create_request_invoice_line(purchase.order_line)
        return res

    def create_request_invoice_line(self, purchase_lines):
        """
        根据采购明细生成付款申请明细
        :param purchase_lines: purchase.order.line，采购单明细
        :return: purchase.payment，采购付款申请明细
        """
        self.ensure_one()
        datas = []
        for line in purchase_lines:
            if line.product_qty > 0:
                avg_price = line.price_total / line.product_qty

                request_line_val = {
                    'partner_id': self.partner_id.id,
                    'product_id': line.product_id.id,
                    'purchase_id': self.id,
                    'sale_tax': line.price_tax,
                    'sale_fee': line.price_total,
                    'total1': line.price_total,
                    'sale_untaxed_fee': line.price_subtotal,
                    'measure_unit': line.product_uom.id,
                    'quantity': line.product_qty,
                    'avg_price': avg_price,
                    'purchase_line_id': line.id,
                    'currency_id': self.currency_id.id or False,
                }
                datas.append(request_line_val)
        if datas:
            return self.env['purchase.payment'].create(datas)
        return self.env['purchase.payment']
